package cn.jfast.framework.web.core;

import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

class XmlDefinitionsReader {

    /**
     * 默认配置文件位置
     */
    public static final String DEFAULT_CONFIG_LOCATION = "jfast-config.xml";

    private Map<String, String> propMap = new HashMap<String, String>();

    public Map<String, String> parser() {
        SAXParserFactory sf = SAXParserFactory.newInstance();
        try {
            SAXParser parser = sf.newSAXParser();
            DefaultHandler handler = new DefaultHandler() {
                @Override
                public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
                    super.startElement(uri, localName, qName, attributes);
                    for (int i = 0; i < attributes.getLength(); i++) {
                        String attrName = attributes.getQName(i);
                        String attrValue = attributes.getValue(i);
                        propMap.put(attrName, attrValue);
                    }
                }
            };
            parser.parse(new InputSource(Thread.currentThread().getContextClassLoader().getResource("/") + DEFAULT_CONFIG_LOCATION), handler);
        } catch (ParserConfigurationException e) {
            e.printStackTrace();
        } catch (SAXException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return propMap;
    }

}
